package com.logic.landseaserver.models.rental.util;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

/**
 * 
 *
 * 项目名称：system-server</br>
 * 类名称：YingShiSignVerifyUtil</br>
 * 类描述：银石签名及验签</br>
 * 创建人：Crystal</br>
 * 创建时间：2018年03月07日 下午8:41:29</br>
 * 
 * @version 1.0
 *
 */
public class YingShiSignVerifyUtil
{
    private static final Logger LOG = LoggerFactory.getLogger(YingShiSignVerifyUtil.class);
    
    public final static String SIGN = "Sign";
    
    // 签名
    public static String sign(JsonObject jsObj, String key)
    {
        List<String> list = new ArrayList<String>();
        Set<Entry<String, JsonElement>> set = jsObj.entrySet();
        
        for (Entry<String, JsonElement> entry : set)
        {
            String field = entry.getKey();
            JsonElement value = entry.getValue();
            if (!SIGN.equals(field) && !value.isJsonArray() && StringUtils.isNotEmpty(field))
            {
                String valueStr = value.getAsString();
                if (StringUtils.isNotEmpty(valueStr))
                {
                    list.add(field + "=" + value.getAsString());
                }
            }
        }
        
        list.add("Key=" + key);
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++)
        {
            if (i > 0)
            {
                sb.append("&");
            }
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        try
        {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] bytes = messageDigest.digest(result.getBytes("UTF-8"));
            result = Hex.encodeHexString(bytes);
        }
        catch (Exception e)
        {
            // 忽略加密方式和字符集不支持异常
            LOG.error("SignVerifyUtil error|key=" + key + "|" + jsObj.toString(), e);
        }
        return result;
    }
    
    // 验签
    public static boolean verify(JsonObject jsObj, String key)
    {
        JsonElement jsonElementsign = jsObj.get(SIGN);
        if (null == jsonElementsign)
        {
            return false;
        }
        
        String sign = jsonElementsign.getAsString();
        if (StringUtils.isEmpty(sign))
        {
            return false;
        }
        
        return sign.equals(sign(jsObj, key));
    }
}
